package me.khrystal.net;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import me.khrystal.activities.MainActivity;
import me.khrystal.activities.SplashActivity;
import me.khrystal.fragments.ProgressFragment;
import me.khrystal.model.BaseResponse;
import me.khrystal.util.Global;
import me.khrystal.util.LogUtils;


/**
 * Created by khrystal on 15/7/23.
 */
public abstract class RequestServerTask<T extends BaseResponse> extends AsyncTask<Void, Void, String> {
    private static final String LOG_TAG = RequestServerTask.class.getSimpleName();

    String default_err_msg;
    Class<T> responseType;
    String progressTitle;
    Activity mActivity;
    Fragment mFragment;
    ProgressFragment progressFragment;
    View viewForSnackbar;
    String errorType;

    public RequestServerTask(Class<T> responseType) {
        super();
        this.responseType = responseType;
    }

    public RequestServerTask(Class<T> responseType,Object parent){
        super();
        this.responseType = responseType;
        if (parent instanceof Activity) {
            mActivity = (Activity) parent;
        } else if (parent instanceof Fragment) {
            mFragment = (Fragment) parent;
        }
    }

    /*public RequestServerTask(Class<T> responseType, Object parent, String progressTitle,String errorType) {
        this.(Class<T> responseType,Object)
    }*/

    public RequestServerTask(Class<T> responseType, Object parent, String progressTitle) {
        super();
        this.responseType = responseType;
        if (parent instanceof Activity) {
            mActivity = (Activity) parent;
        } else if (parent instanceof Fragment) {
            mFragment = (Fragment) parent;
        }
        this.progressTitle = progressTitle;
    }

    public RequestServerTask setDefaultErrMsg(String errMsg) {
        this.default_err_msg = errMsg;
        return this;
    }

    public RequestServerTask setDefaultErrMsg(int errMsg) {
        this.default_err_msg = Global.getContext().getString(errMsg);
        return this;
    }

    public RequestServerTask setSnackbarView(View view) {
        this.viewForSnackbar = view;
        return this;
    }

    @Override
    protected String doInBackground(Void... params) {
        return requestServer();
    }

    protected abstract String requestServer();

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        T result;
        try {
            if (s != null) {
                result = Global.getGson().fromJson(s, responseType);
            } else {
                result = null;
            }
            if (result != null && result.ret) {
                onSuccess(result);
            } else {
                boolean handled = onFailure(result);
                if (!handled) {
                    /**
                     * this demo just show hotfix
                     * this area can work more things
                     */
                    if (mActivity!=null){
                        if (mActivity instanceof SplashActivity){
                            LogUtils.d("CheckPatch","can't access host server!");
                            Toast.makeText(mActivity,"access host error!",Toast.LENGTH_LONG).show();
                            //TODO skip to MainActivity
                            Intent intent = new Intent(mActivity, MainActivity.class);
                            mActivity.startActivity(intent);
                            mActivity.finish();
                        }
                    }


                    if (viewForSnackbar != null) {

                    } else {

                    }
                }
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, Log.getStackTraceString(e));
        } finally {
            onFinish();
        }
    }

    protected abstract void onSuccess(T result);

    protected void onStart() {
        if (!TextUtils.isEmpty(progressTitle)) {
           //can display ProgressFragment
        }
    }

    protected void onFinish() {
        if (progressFragment != null) {
            progressFragment.dismissAllowingStateLoss();
            progressFragment.dismiss();
            progressFragment = null;
        }
    }

    protected boolean onFailure(final T result) {
        return false;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        onStart();
    }

    public void start() {
        this.executeOnExecutor(THREAD_POOL_EXECUTOR);
    }
}
